from datetime import date, datetime
from horseanalysis.model.race import Race
from horseanalysis.model.race_batch import RaceBatch
from horseanalysis.lib.hkjc_fetcher.win_place_fetcher import WinPlaceFetcher
from horseanalysis.lib.hkjc_fetcher.quinella_fetcher import QuinellaFetcher
from horseanalysis.lib.hkjc_fetcher.quinella_place_fetcher import QuinellaPlaceFetcher
from horseanalysis.lib.hkjc_fetcher.investment_fetcher import InvestmentFetcher
from horseanalysis.model.probability_sets.quinella_probability_result import QuinellaProbabilityResult
from horseanalysis.model.probability_sets.quinella_place_probability_result import QuinellaPlaceProbabilityResult
from horseanalysis.model.probability_sets.place_probability_result import PlaceProbabilityResult
import re

class CurrentRaceFetcher:
  def __init__(self):
    self.race = Race.get_current_race()
  
  def should_fetch_current_race(self):
    if self.race:
      time_remaining = self.race.race_time - datetime.now()
      return time_remaining.days == 0 and time_remaining.seconds < 1800    # 30 miniutes before it race
    else:
      return False
    
  def init_batch_time(self):
    # not create it unless it is neccessary before fetch real data
    if 'batch_time' not in self.__dict__:
      self.batch_time = RaceBatch.create_or_retrieve(self.race, datetime.now())
    
  def fetch_current_race_data(self):
    if self.race:
      for fetcher in [WinPlaceFetcher, QuinellaFetcher, QuinellaPlaceFetcher, InvestmentFetcher]:
        self.get_data(fetcher)
      
      if PlaceProbabilityResult.prerequisites_checking(self.batch_time):
        for probability_result in [QuinellaProbabilityResult, QuinellaPlaceProbabilityResult, PlaceProbabilityResult]:
          probability_result.analyze_batch_if_not_existed(self.batch_time)

  def get_data(self, fetcher_class):
    self.init_batch_time()
    if self.race:
      fetcher = fetcher_class(self.race, self.batch_time)
      fetcher.getResult()
  